import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:tin_flutter/app/global.dart';
import 'package:tin_flutter/app/network/http_service.dart';
import 'package:tin_flutter/app/tools/logger.dart';

import 'main_state.dart';

class MainLogic extends GetxController {
  final state = MainState();

  @override
  void onReady() {
    super.onReady();
    // 获取首页内容
    getHomeContent();
  }

  @override
  void onClose() {
    // TODO: implement onClose
    super.onClose();
  }

  /// 获取首页内容
  void getHomeContent() async {
    HttpService.getHomeContent().then((value) {
      logger('请求首页数据成功：$value');
      // 轮播广告列表
      state.advertiseList = value.advertiseList.obs;
      // 品牌列表
      state.brandList = value.brandList.obs;
      // 秒杀专区
      state.flashPromotion = value.homeFlashPromotion.obs;
      // 新品列表
      state.newProductList = value.newProductList.obs;
      // 热门列表
      state.hotProductList = value.hotProductList.obs;
    });
  }

  /// 获取推荐商品列表
  /// * [isRefresh] 是否刷新
  void getRecommendProduct({bool isRefresh = false}) async {
    if (!isRefresh && !state.hasMore.value) return;

    state.isLoading.value = true;

    if (isRefresh) {
      state.currentPage.value = 1;
    }

    try {
      final response = await HttpService.getRecommendProductList(
        state.currentPage.value,
        6,
      );

      if (response.isNotEmpty) {
        if (isRefresh) {
          state.recommendProductList.clear();
        }
        logger('添加商品成功：${response.length}');
        state.recommendProductList.addAll(response);
        state.currentPage.value++;
        state.hasMore.value = response.length == 6; // 判断是否还有更多数据
      }
    } catch (e) {
      logger('获取品牌推荐列表失败：$e');
    } finally {
      state.isLoading.value = false;
    }
  }

  /// 上拉加载更多
  void onLoadMore() {
    getRecommendProduct();
  }



  Future<void> checkPermission(BuildContext context) async {
    ///android权限申请需要在AndroidManifest.xml里添加对应的权限声明
    ///iOS
    // You can request multiple permissions at once.
    Map<Permission, PermissionStatus> statuses =
        await [Permission.phone, Permission.storage, Permission.camera].request();
    statuses.forEach((key, value) {
      if (value.isDenied) {
        ///被拒绝了
        showToast('permissionDenied'.tr, type: ToastType.error);
        return;
      }
    });
  }

  changeLanguage() {
    var locale = Get.locale;
    if (locale?.languageCode == 'cn') {
      Get.updateLocale(Locale('en', 'EN'));
    } else {
      Get.updateLocale(Locale('cn', 'ZH'));
    }
  }
}
